import request from "../../axios";
import { useEffect, useState } from "react";
import {
  Input,
  Select,
  Space,
  DatePicker,
  Button,
  Table,
  Spin,
  message,
  Pagination,
} from "antd";
import dayjs from "dayjs";
import { useSelector } from "react-redux";
import "./index.css";
import haneleExport from "../../component/Export";
import { render } from "@testing-library/react";

const { RangePicker } = DatePicker;

// 定义合同产品的类型
interface ContractProduct {
  productName: string;
  productModel: string;
  productSpecification: string;
  unitPrice: number | string;
  quantity: number;
  totalPrice: number | string;
  remarks: string;
}

// 定义合同的类型
interface Contract {
  id: number;
  code: string;
  name: string;
  contractType: string;
  status: string;
  products: ContractProduct[];
  contractTime: string;
  address: string;
}

interface ContType {
  [key: string]: string;
}
const contractTypes: any[] = [
  {
    label: "销售合同",
    value: '1'
  },
  {
    label: "合作协议",
    value: '2'
  },
  {
    label: "售后合同",
    value: '3'
  },
  {
    label: "租赁/分期合同",
    value: '4'
  },
  {
    label: "借试用合同",
    value: '6'
  },
  {
    label: "其他",
    value: '5'
  }
]

const CtManage: React.FC = () => {
  const counter = useSelector((state: any) => state.counter.data);
  // 定义状态的类型
  const [allData, setAllData] = useState<any>([]);
  const [keyword, setKeyword] = useState<string>("");
  const [type, setType] = useState<string | number>("0");
  const [nowTime, setNowTime] = useState<string[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [current, setCurrent] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  // console.log(counter.corpId,'counter')
  // sessionStorage.setItem('counter', JSON.stringify(counter))

  // 获取数据的函数
  const getInitData = async (
    keywords: string = keyword,
    types: string | number = type,
    nowTimes: string[] = nowTime,
    page: number = current
  ): Promise<void> => {
    try {
      setLoading(true);
      const { data } = await request.get("/route/api/contracts", {
        accessToken: "",
        enterpriseId: counter?.corpId,
        keyword: keywords,
        contractType: types === "0" ? null : types,
        minContractTime: nowTimes[0] ?? null,
        maxContractTime: nowTimes[1] ?? null,
        pageNum: page,
        pageSize: pageSize,
      });
      setAllData(data);
    } catch (error) {
      message.error("请求失败");
    } finally {
      setLoading(false);
    }
  };

  // 重置的函数
  const onReset = async (): Promise<void> => {
    setKeyword("");
    setType("0");
    setNowTime([]);
    setCurrent(1);
    await getInitData("", "0", [], 1);
  };

  const handleExport = async () => {
    message.success("开始下载");
    try {
      const response = await request.get(
        "/route/api/exportContracts",
        {
          accessToken: "",
          enterpriseId: counter?.corpId,
          keyword: keyword,
          contractType: type === "0" ? null : type,
          minContractTime: nowTime[0] ?? null,
          maxContractTime: nowTime[1] ?? null,
        },
        true
      );
      haneleExport(response, "合同信息");
    } catch (error) {
      message.error("请求失败");
    }
  };

  const handleChange = (current: number, size: number) => {
    setCurrent(current);
    setPageSize(size);
  };

  useEffect(() => {
    getInitData();
  }, [current, pageSize]);

  const columns: any[] = [
    {
      title: "关联项目名",
      dataIndex: "name",
      width: "auto",
    },
    {
      title: "跨区域",
      dataIndex: "transRegional",
      width: "auto",
    },
    {
      title: "销售负责人",
      dataIndex: "contractSalesman",
      width: "auto",
    },
    {
      title: "成交日期",
      dataIndex: "contractTime",
      width: "auto",
    },
    {
      title: "合同金额",
      dataIndex: "contractAmount",
      render: (val: number | string) => {
        return `￥${val || 0}`;
      },
    },
    {
      title: "产品",
      dataIndex: "products",
      render: (products: any) => {
        if (!products || products.length === 0) {
          return null;
        }
        return (
          <div>
            {products.map((product: any, ind: number) => (
              <p>
                {ind + 1}、{product.productName} x
                {(product?.quantity || 0) + "台"}
              </p>
            ))}
          </div>
        );
      },
    },
    {
      title: "已发货额",
      dataIndex: "amountShipped",
      render: (val: number | string) => {
        return `￥${val || 0}`;
      },
    },
    {
      title: "已回款额",
      dataIndex: "amountReturned",
      render: (val: number | string) => {
        return `￥${val || 0}`;
      },
    },
    {
      title: "逾期应收额",
      dataIndex: "overdueAmount",
      render: (val: number | string) => {
        return `￥${val || 0}`;
      },
    },
  ];

  return (
    <div className="container">
      <div className="table-content">
        <Spin tip="数据加载中" spinning={loading}>
          <div className="search-container">
            <div className="search-filters">
              <Space direction="vertical" className="filter-group">
                <span className="filter-label">关键词</span>
                <Input
                  className="filter-input"
                  value={keyword}
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                    setKeyword(e.target.value);
                  }}
                  placeholder="合同名称、合同编号、产品名"
                />
              </Space>
              <Space direction="vertical" className="filter-group">
                <span className="filter-label">合同类型</span>
                <Select
                  className="filter-select"
                  value={type}
                  onChange={(val: string | number) => {
                    setType(val);
                  }}
                >
                  <Select.Option value="0">全部</Select.Option>
                  {contractTypes.map((item) => {
                    return <Select.Option value={item.label}>{item.label}</Select.Option>;
                  })}
                </Select>
              </Space>
              <Space direction="vertical" className="filter-group">
                <span className="filter-label">成交日期</span>
                <RangePicker
                  className="filter-range-picker"
                  value={
                    nowTime?.[0]
                      ? [dayjs(nowTime[0]), dayjs(nowTime[1])]
                      : [null, null]
                  }
                  onChange={(val: any) => {
                    if (val === null) {
                      setNowTime([]);
                      return;
                    }
                    setNowTime([
                      dayjs(val[0]).format("YYYY-MM-DD"),
                      dayjs(val[1]).format("YYYY-MM-DD"),
                    ]);
                  }}
                />
              </Space>
            </div>
            <div className="search-buttons">
              <Button
                key={"search"}
                className="search-button"
                onClick={() => {
                  setCurrent(1);
                  getInitData(undefined, undefined, undefined, 1);
                }}
              >
                查询
              </Button>
              <Button
                key={"reset"}
                className="reset-button"
                onClick={() => onReset()}
              >
                重置
              </Button>
              <Button
                key={"export"}
                className="export-button"
                onClick={async () => handleExport()}
              >
                导出Excel
              </Button>
            </div>
          </div>
          {allData?.data?.length ? (
            allData?.data?.map((item: any, ind: number) => {
              return (
                <div className="table-container" key={item.id || ind}>
                  <p className="contract-info">
                    <Button
                      style={{ width: "fit-content" }}
                      className={"contract-status-button-left" + contractTypes.find((v)=>{
                        return v.label===item.contractType
                      })?.value}
                    >
                      {item.contractType}
                    </Button>
                    <span className="contract-number">{item.code}</span>
                    <span className="contract-name">{item.name}</span>
                    <Button className={"contract-status-button"}>
                      {item.status}
                    </Button>
                  </p>
                  <Table
                    columns={columns}
                    className="device-log-table"
                    dataSource={[item]}
                    pagination={false}
                    scroll={{ y: 500, x: 1600 }}
                  />
                  <p className="contract-info">
                    <span className="contract-name">
                      <span className="contract-title">合同时间:</span>{" "}
                      {item.contractTime}
                    </span>
                    <span className="contract-name" style={{ float: "right" }}>
                      <span className="contract-title">合同地址:</span>{" "}
                      {item.address || "暂无地址"}
                    </span>
                  </p>
                </div>
              );
            })
          ) : (
            <Table
              columns={columns}
              className="device-log-table"
              dataSource={[]}
              pagination={false}
              scroll={{ y: 500, x: 1600 }}
            />
          )}
        </Spin>
      </div>
      <Pagination
        current={current}
        pageSize={pageSize}
        pageSizeOptions={["5", "10", "20"]}
        showSizeChanger
        onChange={handleChange}
        total={allData?.totalCount}
        style={{ marginTop: "20px", float: "right" }}
      />
    </div>
  );
};

export default CtManage;
